package com.teamone.etl.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;

/**
 @author WangZhuoRan */
public class VerifyUtil {

    private static final int PHONE_MAX_LENGTH = 11;
    private static final int LICENSE_MAX_LENGTH = 18;
    private static final int MAX = 2 << 4 - 1;

    public static boolean phone(String phone) {
        String regex = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(17[013678])|(18[0-9]))\\d{8}$";
        if(phone.length() != PHONE_MAX_LENGTH){
            return false;
        }else{
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(phone);
            return m.matches();
        }
    }

    public static boolean license(String license){
        if(StringUtils.isEmpty(license) || license.length() != LICENSE_MAX_LENGTH) {
            return false;
        }
        String regex = "^([159Y]{1})([1239]{1})([0-9ABCDEFGHJKLMNPQRTUWXY]{6})([0-9ABCDEFGHJKLMNPQRTUWXY]{9})([0-90-9ABCDEFGHJKLMNPQRTUWXY])$";
        if (!license.matches(regex)) {
            return false;
        }
        String str = "0123456789ABCDEFGHJKLMNPQRTUWXY";
        int[] ws = { 1, 3, 9, 27, 19, 26, 16, 17, 20, 29, 25, 13, 8, 24, 10, 30, 28 };
        String[] codes = new String[2];
        codes[0] = license.substring(0, license.length() - 1);
        codes[1] = license.substring(license.length() - 1);
        int sum = 0;
        for (int i = 0; i < LICENSE_MAX_LENGTH-1; i++) {
            sum += str.indexOf(codes[0].charAt(i)) * ws[i];
        }
        int c18 = 31 - (sum % 31);
        if (c18 == MAX) {
            c18 = 'Y';
        } else if (c18 == MAX-1) {
            c18 = '0';
        }
        return str.charAt(c18) == codes[1].charAt(0);
    }

}
